package ystp.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ystp.model.Ysrenyuanfenpei;
import ystp.model.Ysuser;
import ystp.model.Ysxiangmu;
import ystp.service.*;
import ystp.support.CreateXLS;
import ystp.support.JsonResult;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("renyuanfenpei")
public class YsrenyuanfenpeiController {

    @Value("${userfilepath}")
    private String userfilepath;

    @Resource
    YsrenyuanfenpeiService ddService;

    @Resource
    YsxiangmuService ddYsxiangmuService;

    @Resource
    YsuserService ddYsuserService;

    @Resource
    KangjunyaowuService ddKangjunyaowuService;

    @Resource
    KangjunyaowujieguoService ddKangjunyaowujieguoService;


    public Logger log = LoggerFactory.getLogger(YsrenyuanfenpeiController.class);

    @RequestMapping("findRenyuanFenpeiByXiangmuId")
    public JsonResult<?> findRenyuanFenpeiByXiangmuId(@RequestParam("xiangmuid") String ppxianmguId){
        try {
            return JsonResult.getSuccessResult(ddService.findRenyuanFenpeiByXiangmuId(ppxianmguId));

        }catch (Exception e) {
            e.printStackTrace();
            log.error("renyuanfenpei/findRenyuanFenpeiByXiangmuId:error",e);
            return JsonResult.getErrorResult("renyuanfenpei/findRenyuanFenpeiByXiangmuId:error " + e.getMessage());
        }
    }

    @RequestMapping("add")
    public JsonResult<?> add(
            @RequestParam("xiangmuid") String ppxiangmuId,
            @RequestParam("userid") String ppuserId,
            HttpServletRequest request){
        try{
            if(ddService.findbyUserIDandXiangmuId(ppuserId,ppxiangmuId).size()>0){
                return JsonResult.getErrorResult("加入失败！该人员已加入当前活动项目中。");
            }
            if(ddService.findUserNumberByXiangmuId(ppxiangmuId).size()>=ddYsxiangmuService.findOne(ppxiangmuId).getZhuangjiashu()){
                return JsonResult.getErrorResult("加入失败！该项目人员已满。");
            }

            Ysrenyuanfenpei mmRenyuanfenpei=new Ysrenyuanfenpei();
            mmRenyuanfenpei.setId(UUID.randomUUID().toString());
            mmRenyuanfenpei.setXiangmuid(ppxiangmuId);
            mmRenyuanfenpei.setUserid(ppuserId);
            mmRenyuanfenpei.setIssubmit(0);
            HttpSession session = request.getSession();
            mmRenyuanfenpei.setCreatetime(new Date());
            mmRenyuanfenpei.setCreateby(session.getAttribute("Id").toString());
            return ddService.add(mmRenyuanfenpei)==true? JsonResult.getSuccessResult("新增成功")
                    : JsonResult.getErrorResult("新增失败");
        }catch (Exception e) {
            e.printStackTrace();
            log.error("renyuanfenpei/add:error",e);
            return JsonResult.getErrorResult("renyuanfenpei/add:error " + e.getMessage());
        }

    }

    @RequestMapping("checkIsAllSubmited")
    public JsonResult<?> checkIsAllSubmited(
            @RequestParam("xiangmuid") String ppxiangmuId,
            @RequestParam("userid") String ppuserId){

        List<Ysrenyuanfenpei> mmUserList=ddService.findUserByXiangmuId(ppxiangmuId);
        Integer mmSubmitedCount=ddService.getSubmitedCount(ppxiangmuId);
        if(mmUserList.size()==mmSubmitedCount){
            return  JsonResult.getSuccessResult("1");
        }else {
            return  JsonResult.getSuccessResult("0");
        }
    }

    @RequestMapping("checkIsSubmited")
    public JsonResult<?> checkIsSubmited(
            @RequestParam("xiangmuid") String ppxiangmuId,
            @RequestParam("userid") String ppuserId){
        List<Ysrenyuanfenpei> list=ddService.findbyUserIDandXiangmuId(ppuserId,ppxiangmuId);
        if(list.size()<1){
            return JsonResult.getErrorResult("错误，人员-项目分配信息不存在");
        }
        if("1".equals(list.get(0).getIssubmit().toString())){
            return  JsonResult.getSuccessResult("1");
        }else {
            return  JsonResult.getSuccessResult("0");
        }
    }


    @RequestMapping("resetpsw")
    @Transactional
    public JsonResult<?> resetpsw(
            @RequestParam("xiangmuid") String ppxiangmuId,
            HttpServletRequest request){
        try{

            List<Map<String, Object>> mmList=ddService.findRenyuanFenpeiByXiangmuId(ppxiangmuId);
            if(mmList.size()==0){
                JsonResult.getErrorResult("重置失败，当前项目不存在评审委员");
            }
            for(Map<String, Object> mmMap:mmList){
                String mmUserid=mmMap.get("userid").toString();
                String mmUUid=UUID.randomUUID().toString();
                Ysuser mmYsuser=ddYsuserService.findOne(mmUserid);
                mmYsuser.setUpdatetime(new Date());
                HttpSession session = request.getSession();
                mmYsuser.setUpdateby(session.getAttribute("Id").toString());
                mmYsuser.setPassword(mmUUid.substring(0,6));
                mmYsuser.setShifouxiugai("0");
                ddYsuserService.modify(mmYsuser);
            }

            return  JsonResult.getSuccessResult("1");
        }catch (Exception e) {
            e.printStackTrace();
            log.error("renyuanfenpei/resetpsw:error",e);
            return JsonResult.getErrorResult("renyuanfenpei/resetpsw:error " + e.getMessage());
        }
    }

    @RequestMapping("delete")
    public JsonResult<?> delete(@RequestParam("id") String ppId){
        try {

            return ddService.delete(ppId)==true? JsonResult.getSuccessResult("删除成功")
                    : JsonResult.getErrorResult("删除失败");

        }catch (Exception e) {
            e.printStackTrace();
            log.error("renyuanfenpei/delete:error",e);
            return JsonResult.getErrorResult("renyuanfenpei/delete:error " + e.getMessage());
        }
    }

    @RequestMapping("submit")
    public JsonResult<?> submit(
            @RequestParam("xiangmuid") String ppxiangmuId,
            @RequestParam("userid") String ppuserId,
            HttpServletRequest request){
        try{
            List<Ysrenyuanfenpei>  list=ddService.findbyUserIDandXiangmuId(ppuserId,ppxiangmuId);
            if(list.size()<1){
                return JsonResult.getErrorResult("提交失败，人员-项目分配信息不存在");
            }

            int mmjicaiyaoshu=ddKangjunyaowujieguoService.getGuizeCount(ppuserId,ppxiangmuId,"1");//规则1为集采药
            int mmtotaljicaiyaoshu=ddKangjunyaowuService.findAllByXiangmuIdAndGuizebianhao(ppxiangmuId,"1").size();
            if(mmjicaiyaoshu!=mmtotaljicaiyaoshu){
                return JsonResult.getErrorResult("提交失败，集采药未勾选完毕");
            }


            Integer mmpinzhongshu=ddKangjunyaowujieguoService.getVoitedPinzhongList(ppxiangmuId,ppuserId).size();
            if(mmpinzhongshu>48){
                return JsonResult.getErrorResult("提交失败，勾选品种数超过48");
            }

            if(ddKangjunyaowujieguoService.getKangJunResultCount(ppxiangmuId,ppuserId,"1")>79){
                return JsonResult.getErrorResult("提交失败，勾选品规数超过79");
            }



            List<Map<String, Object>> mmGuizeList=ddKangjunyaowuService.findGuizebianhaoByXiangmuId(ppxiangmuId);
            for (Map<String, Object> mmGuizeMap:mmGuizeList){
                if(mmGuizeMap.get("guizebianhao")!=null&&!"".equals(mmGuizeMap.get("guizebianhao").toString())){
                    String mmGuizebianhao=mmGuizeMap.get("guizebianhao").toString();
                    Integer mmXianzhishu=Integer.valueOf(mmGuizeMap.get("xianzhishu").toString());
                    int mmvotedagreedcount=ddKangjunyaowujieguoService.getGuizeCount(ppuserId,ppxiangmuId,mmGuizebianhao);
                    if("0".equals(mmGuizebianhao)&&mmXianzhishu!=mmvotedagreedcount){
                        return JsonResult.getErrorResult("提交失败0，不满足限制要求");
                    }
                    if("2".equals(mmGuizebianhao)&&mmXianzhishu!=mmvotedagreedcount){
                        return JsonResult.getErrorResult("提交失败2，不满足限制要求");
                    }
                    if("3".equals(mmGuizebianhao)&&mmvotedagreedcount>mmXianzhishu){
                        return JsonResult.getErrorResult("提交失败，品规4、10、11、12、18最多5选4");
                    }
                    if("4".equals(mmGuizebianhao)&&mmvotedagreedcount>mmXianzhishu){
                        return JsonResult.getErrorResult("提交失败，品规23、24、25、26最多4选3");
                    }
                    if("5".equals(mmGuizebianhao)&&mmvotedagreedcount>mmXianzhishu){
                        return JsonResult.getErrorResult("提交失败，品规19、20、21、22最多4选2");
                    }
                    if("6".equals(mmGuizebianhao)&&mmvotedagreedcount>mmXianzhishu){
                        return JsonResult.getErrorResult("提交失败，品规27、31最多2选1");
                    }
                    if("7".equals(mmGuizebianhao)&&mmvotedagreedcount>mmXianzhishu){
                        return JsonResult.getErrorResult("提交失败7，不满足限制要求");
                    }
                    if("8".equals(mmGuizebianhao)&&mmvotedagreedcount>mmXianzhishu){
                        return JsonResult.getErrorResult("提交失败，品规37、38、39最多3选2");
                    }


//                    if("9".equals(mmGuizebianhao)&&(mmvotedagreedcount>mmXianzhishu||mmvotedagreedcount==0)){
//                        return JsonResult.getErrorResult("提交失败9，不满足限制要求");
//                    }
//                    if("10".equals(mmGuizebianhao)&&(mmvotedagreedcount>mmXianzhishu||mmvotedagreedcount==0)){
//                        return JsonResult.getErrorResult("提交失败10，不满足限制要求");
//                    }
                    if("11".equals(mmGuizebianhao)&&mmvotedagreedcount>mmXianzhishu){
                        return JsonResult.getErrorResult("提交失败，品规63、64、65最多3选2");
                    }
//                    if("12".equals(mmGuizebianhao)&&mmvotedagreedcount>mmXianzhishu){
//                        return JsonResult.getErrorResult("提交失败12，不满足限制要求");
//                    }
                    if("12".equals(mmGuizebianhao)&&mmvotedagreedcount!=mmXianzhishu){
                        return JsonResult.getErrorResult("提交失败，79、80、81须选满两个");
                    }

                    if("13".equals(mmGuizebianhao)&&mmvotedagreedcount>mmXianzhishu){
                        return JsonResult.getErrorResult("提交失败13，不满足限制要求");
                    }
                    if("14".equals(mmGuizebianhao)&&mmvotedagreedcount>mmXianzhishu){
                        return JsonResult.getErrorResult("提交失败14，不满足限制要求");
                    }

                    if("3.1".equals(mmGuizebianhao)||"5.1".equals(mmGuizebianhao)||"7.1".equals(mmGuizebianhao)){
                        mmvotedagreedcount=ddKangjunyaowujieguoService.getZiGuizeCount(ppuserId,ppxiangmuId,mmGuizebianhao);
                        if(mmvotedagreedcount>mmXianzhishu){
                            return JsonResult.getErrorResult("提交失败"+mmGuizebianhao+"，不满足限制要求");
                        }
                    }



                }

            }


            Boolean isQuefenlei=false;
            String mmFenleiErr="";
            List<Map<String, Object>> mmFeileiList=ddKangjunyaowuService.findFeileiByXiangmuId(ppxiangmuId);
            for(Map<String, Object> mmFeileiMap:mmFeileiList){
                String mmFeilei=mmFeileiMap.get("fenlei").toString();
                int mmFeileiNumber=ddKangjunyaowuService.findByXiangmuIdAndFenlei(ppxiangmuId,mmFeilei).size();
                int mmFeileiTaotaiNumber=ddKangjunyaowuService.findByXiangmuIdAndFenleiAndGuizebianhao(ppxiangmuId,mmFeilei,"0").size();

                List<Map<String, Object>> mmResiltFeilenList=ddKangjunyaowujieguoService.getVoitedFenleiList(ppxiangmuId,ppuserId,mmFeilei);
                if((mmResiltFeilenList.size()==0)&&mmFeileiNumber!=mmFeileiTaotaiNumber){
                    isQuefenlei=true;
                    mmFenleiErr=mmFenleiErr+","+"【"+mmFeilei+"】";
                }
            }
            if(isQuefenlei){
                return JsonResult.getErrorResult("提交失败"+mmFenleiErr+"分类至少勾选一个");
            }


//            int mmTotal=0;
//            int mmVoted=0;
//            Ysxiangmu mmYsxiangmu=ddYsxiangmuService.findOne(ppxiangmuId);
//            if("1".equals(mmYsxiangmu.getXiangmuleixing())){
//                mmTotal=ddKangjunyaowuService.getVoteCount(ppxiangmuId);
//                mmVoted=ddKangjunyaowujieguoService.getKangJunResultCount(ppxiangmuId,ppuserId,"");
//            }

//            if("6".equals(mmYltpXiangmu.getXiangmuleixing())){
//                mmTotal=ddTiwaizhenduanService.getVoteCount(ppxiangmuId);
//                mmVoted=ddTiwaijieguoService.getTiWaiResultCount(ppxiangmuId,ppuserId,"");
//            }

//            if(mmTotal!=mmVoted){
//                return JsonResult.getErrorResult("提交失败，存在未投票条目");
//            }

            Ysrenyuanfenpei mmRenyuanfenpei=ddService.findOne(list.get(0).getId());
            mmRenyuanfenpei.setIssubmit(1);
            mmRenyuanfenpei.setUpdatetime(new Date());
            HttpSession session = request.getSession();
            mmRenyuanfenpei.setUpdateby(session.getAttribute("Id").toString());
            return ddService.update(mmRenyuanfenpei)==true? JsonResult.getSuccessResult("提交成功")
                    : JsonResult.getErrorResult("提交失败");
        }catch (Exception e) {
            e.printStackTrace();
            log.error("renyuanfenpei/submit:error",e);
            return JsonResult.getErrorResult("renyuanfenpei/submit:error " + e.getMessage());
        }

    }
    @RequestMapping("exportRenyuan")
    public String exportRenyuan(HttpServletRequest request, HttpServletResponse response,
                                @RequestParam("xiangmuId") String ppxiangmuid

    ) {
        List<List<String>> mmResultList = new ArrayList<List<String>>();
        List<String> mmTitleList = new ArrayList<String>();

        mmTitleList.add("序号");
        mmTitleList.add("姓名");
        mmTitleList.add("部职别");
        mmTitleList.add("账号");
        mmTitleList.add("密码");
        mmResultList.add(mmTitleList);

        List<Map<String, Object>> mmXiangmuList = ddService.findRenyuanFenpeiByXiangmuId(ppxiangmuid);
        int mmXiangmushu = mmXiangmuList.size();
        if(mmXiangmushu > 0) {
            for (int i = 0; i < mmXiangmushu; i++) {
                Map<String, Object> mmXiangmuMap=mmXiangmuList.get(i);
                String mmXuhao = String.valueOf(i + 1);
                String mmUsername=mmXiangmuMap.get("username")==null ? "" :mmXiangmuMap.get("username").toString();
                String mmBuzhibie=mmXiangmuMap.get("buzhibie")==null ? "" :mmXiangmuMap.get("buzhibie").toString();
                String mmAccount=mmXiangmuMap.get("account")==null ? "" :mmXiangmuMap.get("account").toString();
                String mmPassword=mmXiangmuMap.get("password")==null ? "" :mmXiangmuMap.get("password").toString();

                List<String> mmTempList = new ArrayList<String>();
                mmTempList.add(mmXuhao);
                mmTempList.add(mmUsername);
                mmTempList.add(mmBuzhibie);
                mmTempList.add(mmAccount);
                mmTempList.add(mmPassword);

                mmResultList.add(mmTempList);

            }
        }

        try {
            //取出文档存放的根目录，并去除文件最后的斜杠
            if (userfilepath.endsWith("/")) {
                userfilepath = userfilepath.substring(0, userfilepath.length()-1);
            }

            SimpleDateFormat mmDateFormat = new SimpleDateFormat("yyyyMMdd");
            String mmSavePath = userfilepath +  "/temp/"+mmDateFormat.format(new Date()) + "/";

            CreateXLS.createExcel(mmResultList, mmSavePath,  "weiyuanxinxi_"+ UUID.randomUUID().toString()+".xls",
                    "weiyuanxinxi", request, response);
            return "/ystp/weiyuanxinxi.xls";

        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.getMessage();
        }
    }




}
